import {
    useUserStore
} from "@/store";
import router from "../router/index.js"
import axios from "axios";
import configObj from "@/config"; 
let {
    contentType,
    requestTimeout,
    baseURL,
    tokenName,
} = configObj;

/**
 * axios请求拦截器配置
 * @param config
 * @returns {any}
 */
const requestConf = (config) => {
    const userStore = useUserStore();
    const {
        token
    } = userStore;

    const hasUrl = config && config.url;
    let hasToken = "";
    if (token) {
        hasToken = token;
    }
    const {
        app_id
    } = userStore;
    let hasAppid = "";
    if (app_id) {
        hasAppid = app_id
    }
    if (config.data && config.formData) {
        config.headers = {
            'Content-Type': 'multipart/form-data'
        }
    }
    config.headers['AppID'] = `${hasAppid}`;
    config.headers[tokenName] = `${hasToken}`;
    return config;
};

/**
 * axios响应拦截器
 * @param config 请求配置
 * @param data response数据
 * @param status HTTP status
 * @param statusText HTTP status text
 * @returns {Promise<*|*>}
 */
const handleData = async ({
    config,
    data,
    status,
    statusText
}) => {
    // 假设所有请求都是正确的，直接返回数据
    return data;
};

/**
 * @description axios初始化
 */
const instance = axios.create({
    baseURL,
    timeout: requestTimeout,
    headers: {
        "Content-Type": contentType,
    },
});

// 请求拦截
instance.interceptors.request.use(config => {
    // 记录请求的URL
    console.log('Request URL:', config.url);

    // showLoading()
    // 是否需要设置 token放在请求头
    // config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    // get请求映射params参数
    if (config.method === 'get' && config.data) {
        let url = config.url + '?';
        console.log(config.data)
        for (const propName of Object.keys(config.data)) {
            const value = config.data[propName];
            var part = encodeURIComponent(propName) + "=";
            if (value !== null && typeof(value) !== "undefined") {
                // 对象处理
                if (typeof value === 'object') {
                    for (const key of Object.keys(value)) {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + "=";
                        url += subPart + encodeURIComponent(value[key]) + "&";
                    }
                } else {
                    url += part + encodeURIComponent(value) + "&";
                }
            }
        }
        url = url.slice(0, -1);
        config.data = {};
        config.url = url;
    }
    return config
}, error => {
    console.log(error)
    Promise.reject(error)
})
/**
 * @description axios请求拦截器
 */
instance.interceptors.request.use(requestConf, (error) => {
    ElMessage.error('接口请求异常，请稍后再试~');
    return Promise.reject(error);
});

/**
 * @description axios响应拦截器
 */
instance.interceptors.response.use(
    (response) => handleData(response),
    (error) => {
        let data = error.response?.data;
        let status = error.response?.status;
        let statusText = error.response?.statusText;

        console.error('Error response:', {
            data,
            status,
            statusText
        });

        ElMessage.error(data?.message || `接口请求异常，请稍后重试 (状态码: ${status}, 错误信息: ${statusText})`);
        return Promise.reject(error.response?.data);
    }
);

export default instance;